//
//  ViewController.m
//  UISearchViewController
//
//  Created by LINAICAI on 2017/1/12.
//  Copyright © 2017年 LINAICAI. All rights reserved.
//

#import "LBCityPickerViewController.h"
#import <MJExtension/MJExtension.h>
#import <CoreLocation/CoreLocation.h>
#define INDEX_TITLE_COLOR [UIColor colorWithWhite:0.0 alpha:0.5]
#define SELECT_TITLE_COLOR [UIColor colorWithWhite:0.0 alpha:0.8]
#define SELECT_FONT [UIFont systemFontOfSize:14]

static NSString *const kTableCellHot = @"kTableCellHot";
static NSString *const kTableCellCommon = @"kTableCellCommon";
static CGFloat const kTableRowHeight = 44;
static CGFloat const kTableSectionHeight = 60;

@interface LBCityPickerViewController ()<UISearchControllerDelegate,UISearchResultsUpdating,CLLocationManagerDelegate>
//热门城市
@property(nonatomic , strong)NSMutableArray<LBCityModel *> *hotCitys;
//全部城市
@property(nonatomic , strong)NSMutableArray<LBCityModel *> *allCitys;
//分组索引
@property(nonatomic , strong)NSMutableArray *keys;
//侧索引
@property(nonatomic , strong)NSMutableArray *indexKeys;
//城市名集合
@property(nonatomic , strong)NSMutableArray *cityNames;
//接收数据源结果
@property(nonatomic , strong)NSMutableArray *searchResults;
//关闭按钮
@property(nonatomic , strong)UIBarButtonItem *backButtonItem;
//位置管理器
@property(nonatomic , strong)CLLocationManager *locationManager;
//定位出来的城市
@property(nonatomic , strong)NSString *locationCity;

@end

@implementation LBCityPickerViewController
#pragma mark- Setting|Getting
- (NSMutableArray *)cityNames{
    if (!_cityNames) {
        _cityNames = [NSMutableArray new];
        for (LBCityModel *model in self.allCitys) {
            [_cityNames addObject:model.areaName];
        }
    }
    return _cityNames;
}
- (NSMutableArray *)keys{
    if (!_keys) {
        _keys = [NSMutableArray new];
        for (LBCityModel *model in self.allCitys) {
            [_keys addObject:model.areaKey];
        }
         NSSet *set = [NSSet setWithArray:_keys];
        _keys = [[[set allObjects] sortedArrayUsingSelector:@selector(compare:)]mutableCopy];
        _indexKeys = [NSMutableArray arrayWithArray:_keys];
    }
    return _keys;
}
- (NSMutableArray *)indexKeys{
    if (!_indexKeys) {
        _indexKeys = [NSMutableArray arrayWithArray:self.keys];
    }
    return _indexKeys;
}
- (NSMutableArray<LBCityModel *> *)hotCitys{
    if (!_hotCitys) {
        NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"city.bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
        NSString *plistPath = [bundle pathForResource:@"hotCity" ofType:@"plist"];
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
        _hotCitys = [LBCityModel mj_objectArrayWithKeyValuesArray:array];
    }
    return _hotCitys;
}
- (NSMutableArray<LBCityModel *> *)allCitys{
    if (!_allCitys) {
        NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"city.bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
        NSString *plistPath = [bundle pathForResource:@"allCity" ofType:@"plist"];
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
        _allCitys = [LBCityModel mj_objectArrayWithKeyValuesArray:array];
    }
    return _allCitys;
}
- (NSMutableArray *)searchResults{
    if (!_searchResults) {
        _searchResults = [NSMutableArray new];
    }
    return _searchResults;
}
- (UISearchController *)searchController{
    if (!_searchController) {
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchBar.frame = CGRectMake(0, 0, 0, 44);
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
        _searchController.searchBar.enablesReturnKeyAutomatically = NO;
        _searchController.definesPresentationContext = YES;
        [_searchController.searchBar sizeToFit];
    }
    return _searchController;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        //虽然适配了，但横竖屏切换之后需要reload的，暂时不做这部分逻辑，也并没有很好的支持，一般来说城市地区选择界面都是竖屏
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_tableView setDelegate:(id<UITableViewDelegate> _Nullable)self];
        [_tableView setDataSource:(id<UITableViewDataSource> _Nullable)self];
        [_tableView setTableHeaderView:self.searchController.searchBar];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableCellHot];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableCellCommon];
        [_tableView  setSectionIndexBackgroundColor:[UIColor clearColor]];
        _tableView.sectionIndexColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}
- (UIBarButtonItem *)backButtonItem{
    if (!_backButtonItem) {
        _backButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick:)];
    }
    return _backButtonItem;
}
#pragma mark- Lift Cycle
- (void)loadView{
    [super loadView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.definesPresentationContext = YES;
    [self.view addSubview:self.tableView];
    self.navigationItem.leftBarButtonItem = self.backButtonItem;
    //添加定位城市、热门城市
    [self.indexKeys insertObjects:@[@"定位",@"热门"] atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)]];
    [self.keys insertObjects:@[@"定位城市",@"热门城市"] atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)]];
    
    //一切准备就绪，如果子类想修改部分控件的外观，可以在子类重写以下方法
    [self prepare];
    // Do any additional setup after loading the view, typically from a nib.
}
#pragma mark- Event
- (void)btnClicked:(UIButton *)btn{
    //如果点击的按钮是定位按钮
    if ([btn.titleLabel.text isEqualToString:self.locationCity]) {
        for (LBCityModel *model in self.allCitys) {
            if ([model.areaName containsString:self.locationCity]){
                self.complete(model);
                break;
            }
        }
    }
    else{
        //否则就是热门城市按钮
        if (self.complete) {
            LBCityModel *model = self.hotCitys[btn.tag];
            self.complete(model);
        }
    }

    [self backButtonClick:nil];
}
- (void)backButtonClick:(id)sender{
    [self dismissViewControllerAnimated:YES completion:^{

    }];
}
#pragma mark- Overwrite
- (UIStatusBarStyle)preferredStatusBarStyle NS_AVAILABLE_IOS(7_0){
    return UIStatusBarStyleLightContent;
}
+ (void)load{
    //为了加快速度，在load阶段就加载数据到内容中去
    __block  LBCityPickerViewController *viewController = [self defaultViewController];
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        [viewController allCitys];
        [viewController hotCitys];
        [viewController cityNames];
        [viewController keys];
        [viewController indexKeys];
    });

}
//工厂方法
+ (void)showWithTitle:(NSString *)title fromVc:(UIViewController *)fromVc toVc:(UIViewController *)toVc complete:(void(^)(LBCityModel *city))complete
{
    LBCityPickerViewController *viewController = [self defaultViewController];
    viewController.title = title;
    viewController.complete = complete;
    [fromVc presentViewController:toVc animated:YES completion:nil];
}
+ (instancetype)defaultViewController{
    static LBCityPickerViewController *singleViewController = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleViewController = [[LBCityPickerViewController alloc]init];
    });
    return singleViewController;
}
- (void)prepare{

    

}
- (void)dealloc{

}
- (BOOL)willDealloc {
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark- Delegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    if (!searchController.active) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [self.tableView reloadData];
    }
    else{
        self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
        [self.searchResults removeAllObjects];
        // c忽略大小写，d忽略重音 根据中文和拼音筛选
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"areaName contains [cd] %@ OR areaLetter BEGINSWITH [cd] %@", searchController.searchBar.text,searchController.searchBar.text];
        
        self.searchResults = [[self.allCitys filteredArrayUsingPredicate:searchPredicate]mutableCopy];
        //刷新表格
        [self.tableView reloadData];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.searchController.active) {
        if (section == 0 || section == 1) {
            return 1;
        }
        NSString *key = _keys[section];
        NSMutableArray *array = [NSMutableArray new];
        for (LBCityModel *model in self.allCitys) {
            if ([model.areaKey isEqualToString:key]) {
                [array addObject:model];
            }
        }
        return array.count;
    }
    else{

        return self.searchResults.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.searchController.active) {
        {
            //普通状态
            if (indexPath.section == 0 || indexPath.section == 1){
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableCellHot];
                if (cell == nil)
                {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTableCellHot];
                    [cell.textLabel setFont:SELECT_FONT];
                    [cell.textLabel setTextColor:SELECT_TITLE_COLOR];
                    [cell setBackgroundColor:[UIColor colorWithRed:242/255.f green:242  /255.f blue:242/255.f alpha:1.0]];
                }
                [self configCell:cell IndexPath:indexPath];
                return cell;
            }
            else{
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableCellCommon];
                if (cell == nil) {
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTableCellCommon];
                    cell.textLabel.font = [UIFont systemFontOfSize:15];
                }
                NSString *key = self.keys[indexPath.section];
                NSMutableArray *array = [NSMutableArray new];
                for (LBCityModel *model  in self.allCitys) {
                    if ([model.areaKey isEqualToString:key]) {
                        [array addObject:model];
                    }
                }
                cell.textLabel.text = [array[indexPath.row] areaName];
                return cell;
            }
            
           
        }
        
    }
    else{
        //搜索结果列表
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableCellCommon];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTableCellCommon];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        }
        LBCityModel *model = self.searchResults[indexPath.row];
        cell.textLabel.text = model.areaName;
        return cell;

    }


}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.searchController.active) {
        if (indexPath.section == 0) {
            return kTableSectionHeight;
        }
        else if (indexPath.section == 1){
            NSInteger line = self.hotCitys.count/3;
            if (line != 0)
            {
                if ( self.hotCitys.count%3 != 0)
                {
                    line += 1;
                }
                CGFloat height = 15*2 + 30*line + 20*(line - 1);
                return height;
            }
        }
    }
    return kTableRowHeight;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (!self.searchController.active) {
        return self.keys[section];
    }
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (!self.searchController.active) {
        return self.keys.count;
    }
    return 1;
    
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (!self.searchController.active) {
        return self.indexKeys;
    }
    else
        return nil;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

{
    //点击索引，列表跳转到对应索引的行
    if (!self.searchController.active) {
        [tableView
         scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
         atScrollPosition:UITableViewScrollPositionTop animated:YES];
        return index;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!self.searchController.active) {
        if (indexPath.section == 0 || indexPath.section == 1) {
            return;
        }
        NSString *key = self.keys[indexPath.section];
        NSMutableArray *array = [NSMutableArray new];
        for (LBCityModel *model  in self.allCitys) {
            if ([model.areaKey isEqualToString:key]) {
                [array addObject:model];
            }
        }
        if (self.complete) {
            self.complete(array[indexPath.row]);
        }
    }
    else{
        
        LBCityModel *model = self.searchResults[indexPath.row];
        self.searchController.active = NO;
        self.complete(model);
        
    }
    [self backButtonClick:nil];
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), 30)];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, CGRectGetWidth(view.bounds)-15, CGRectGetHeight(view.bounds))];
    [label setText:self.keys[section]];
    [label setFont:[UIFont systemFontOfSize:14]];
    [label setTextColor:[UIColor lightGrayColor]];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:230/255.f green:230/255.f blue:230/255.f alpha:1.0]];
    return view;
}

- (void)configCell:(UITableViewCell *)cell IndexPath:(NSIndexPath *)indexPath
{
    CGFloat spaceWidth = (self.view.frame.size.width - 80 * 3 - 20)/4;
    
    CGFloat x=15;//文本对齐
    for (UIView *view in cell.contentView.subviews)
    {
        [view removeFromSuperview];
    }
    
    cell.textLabel.text = nil;
    switch (indexPath.section)
    {
        case 0: // 定位城市
        {
            //如果已经定位了，有两个按钮，一个城市，一个重新定位
            if (self.locationCity.length) {
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(x, 15, 80, 30);
                btn.tag = 1;
                [btn setTitle:self.locationCity forState:UIControlStateNormal];
                [btn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                [btn setTitleColor:SELECT_TITLE_COLOR forState:UIControlStateNormal];
                [btn.titleLabel setFont:SELECT_FONT];
                [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btn];
                
                // 加个重定位按钮
                UIButton *restartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                restartBtn.frame = CGRectMake(x + (80+spaceWidth)*(1%3), 15 + (30+20)*(1/3), 80, 30);
                restartBtn.tag = 2;
                [restartBtn setTitle:@"重新定位" forState:UIControlStateNormal];
                [restartBtn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                [restartBtn setTitleColor:SELECT_TITLE_COLOR forState:UIControlStateNormal];
                [restartBtn.titleLabel setFont:SELECT_FONT];
                [restartBtn addTarget:self action:@selector(restartLocation:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:restartBtn];
            }
            else{
                //没有定位过，只有一个定位按钮
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(x, 15, 80, 30);
                [btn setTitle:@"定位" forState:UIControlStateNormal];
                [btn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                [btn setTitleColor:SELECT_TITLE_COLOR forState:UIControlStateNormal];
                [btn.titleLabel setFont:SELECT_FONT];
                [btn addTarget:self action:@selector(startLocation:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btn];
            }
            
        }
            break;
        case 1: // 热门城市
        {
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            for (NSInteger i = 0; i < self.hotCitys.count; i++)
            {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(x + (80+spaceWidth)*(i%3), 15 + (30+20)*(i/3), 80, 30);
                [btn setTitle:[self.hotCitys[i] areaName] forState:UIControlStateNormal];
                [btn setTitleColor:SELECT_TITLE_COLOR forState:UIControlStateNormal];
                [btn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                [btn.titleLabel setFont:SELECT_FONT];
                [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
                btn.tag = i;
                [cell.contentView addSubview:btn];
                
            }
        }
            break;
        default: // 城市列表
        {
            break;
        }
    }
}
#pragma mark- 定位
//开始定位
-(void)startLocation:(id)sender{
    if (![CLLocationManager locationServicesEnabled])
    {
        UIAlertView *alertView = [[UIAlertView alloc ] initWithTitle:@"温馨提示"
                                                             message:@"定位服务未打开"
                                                            delegate:nil
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles: nil];
        [alertView show];
        return;
    }
    
    if ([[[UIDevice currentDevice] systemVersion] integerValue]>=8.0)
    {
        if (!_locationManager) {
            _locationManager = [[CLLocationManager alloc] init];
        }
        if([CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse)
        {
            [_locationManager requestWhenInUseAuthorization];
        }
        _locationManager.delegate = self;
        [_locationManager startUpdatingLocation];
        
    }
    else
    {
        if (!_locationManager) {
            _locationManager = [[CLLocationManager alloc] init];
        }
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
    
    //开始定位
    UITableViewCell *cell=(UITableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    UIActivityIndicatorView *activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    cell.accessoryView=activity;
    [activity startAnimating];
    
    __block UIButton *btn=(UIButton *)sender;
    [btn setTitle:@"定位中..." forState:UIControlStateNormal];
    CGRect frame=btn.frame;
    [UIView beginAnimations:@"Animations" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    //改变它的frame的x,y的值
    frame.size.width=[@"定位中..." length]*20;
    [btn setFrame:frame];
    [UIView commitAnimations];
}
// 重定位
-(void)restartLocation:(UIButton *)btn
{
    UITableViewCell *cell=(UITableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UIButton *sendBtn = (UIButton *)[cell viewWithTag:2];
    [self startLocation:sendBtn];
    
}
#pragma mark --
#pragma mark -- LocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [manager stopUpdatingLocation];
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *dic = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            self.locationCity = [dic valueForKey:@"City"];
            if (!self.searchController.active) {
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }

        }
    }];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorString;
    [manager stopUpdatingLocation];
    
    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code])
    {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"没有权限";
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"未知位置";
            //Do something else...
            break;
        default:
            errorString = @"未知错误";
            break;
    }
    
    
    
}

@end
